import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    currentDate: new Date().getTime(),
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseId: '',
    houseName: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '',
  },
  rules: {
    houseName: [{ required: true, message: '请选择房屋!' }],
    name: [
      { required: true, message: '请填写访客姓名!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能是2-5位的中文字符' },
    ],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    visitDate: [{ required: true, message: '请选择访问日期!' }],
  },
  onLoad() {
    this.getHouseList()
  },
  // 查询我能选择的房屋数组
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/house')
    if (code !== 10000) return wx.utils.toast
    this.setData({ houseList })
  },
  // 选择具体项时触发
  selectHouse(ev) {
    console.log(ev.detail)
    this.setData({
      houseId: ev.detail.id,
      houseName: ev.detail.name,
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  // 弹出时间选择窗
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },

  // 选择时间点击确定
  onconfirm(ev) {
    console.log(ev.detail)
    this.setData({
      visitDate: wx.utils.FormaTime(ev.detail),
      dateLayerVisible: false,
    })
  },
  // 关闭时间选择框
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 确认提交
  async goPassport() {
    if (!this.validate()) return
    const { houseId, name, gender, mobile, visitDate } = this.data
    const {
      code,
      data: { id },
    } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    if (code !== 10000) return wx.utils.toast('提交失败')
    console.log(id)
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
